package com.study.concurrent.A_ThreadManagement.g_CreateDaemonThreadAndRun;

import java.util.Date;
import java.util.Deque;

/**
 * Created by 赵超 on 2017/3/18.
 */
public class CleanerTask extends Thread {
    private Deque<Event> deque;

    public CleanerTask(Deque<Event> deque) {
        this.deque = deque;
        setDaemon(true);
    }

    @Override
    public void run() {
        while (true) {
            Date date = new Date();
            clean(date);
        }
    }

    /**
     * 读取队列的最后一个事件对象，如果这个事件是10秒钟之前创建的，就将他删除并检查下一个
     * 如果有事件被删除，打印该事件的信息，并打印出队列的长度
     *
     * @param date
     */
    private void clean(Date date) {
        long difference; // 用于检查事件的创建时间
        boolean delete; // 删除标记，标记事件是否被删除
        if (deque.size() == 0) {
            return;
        }
        delete = false;
        do {
            Event e = deque.getLast();
            difference = date.getTime() - e.getDate().getTime();
            //System.out.println(difference);
            if (difference > 10 * 1000) {
                System.out.printf("清理 : %s\n", e.getEvent());
                deque.removeLast();
                delete = true;
                //System.out.printf("清理 : 队列deque的长度为 : %d\n", deque.size());
            }
        } while (difference > 10 * 1000);
        if (delete) {
            System.out.printf("清理 : 队列deque的长度为 : %d\n", deque.size());
        }
    }
}
